import re
import time
from collections import Counter

# 日志文件路径
log_file1 = "D:/k12日志分析测试/1.log"
log_file1 = "D:/k12日志分析测试/newk12_center.log"

ip_count_dict = dict()

ip_pattern = r'^(\d+\.){3}\d+'
ip_regex = re.compile(ip_pattern)
ips = list()


# 读取日志文件
def main():
    # 读取日志文件
    start = time.time()
    with open(log_file1, 'r', encoding='utf-8') as f:
        for line in f:
            mo = ip_regex.search(line)
            if mo:
                ips.append(mo.group())
    ip_counter = Counter(ips)
    ip_c = ip_counter.most_common()
    for item in ip_c:
        print("IP 地址:%s,访问次数:%d" % (item[0], item[1]))
    print("*" * 50)
    print("访问总次数:%d" % len(ips))
    end = time.time()
    print('Running time: %.2f Seconds' % (end - start))


if __name__ == '__main__':
    main()
